<template>
  <div class="wraper">
    <el-card class="box-card">
      <div slot="header" class="box-header">
        <span>用户管理</span>
        <el-button style="float: right; padding: 3px 0" type="text"
          >切换视图</el-button
        >
      </div>
      <div>
        <el-table ref="filterTable" :data="filterTableData">
          <el-table-column
            prop="id"
            label="编号"
            sortable
            width="100"
          ></el-table-column>
          <el-table-column prop="name" label="名称" width="100">
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="100">
          </el-table-column>
          <el-table-column prop="phone" label="电话" width="100">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="180"
          ></el-table-column>
          <el-table-column label="地址" width="300">
            <template slot-scope="scope">
              <span v-if="scope.row.address">
                {{ scope.row.address.city }}- {{ scope.row.address.street }}-
                {{ scope.row.address.suite }}
              </span>
            </template>
          </el-table-column>

          <el-table-column>
            <template #header>
              <el-row type="flex" justify="space-between">
                <el-col :span="8">
                  <el-input
                    v-model="searchValue"
                    size="mini"
                    placeholder="输入名称关键字模糊搜索"
                  />
                </el-col>

                <el-col :span="8">
                  <el-button
                    size="medium"
                    type="primary"
                    @click="
                      () => {
                        dialogFormVisible = true;
                      }
                    "
                    >添加新用户<i class="el-icon-plus"></i
                  ></el-button>
                </el-col>
              </el-row>
            </template>

            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleDesc(scope.$index, scope.row)"
                >详情</el-button
              >

              &nbsp;

              <el-popconfirm
                title="你确定要删除此条数据吗？删除了就真没了！"
                @confirm="handleDelete(scope.row.id)"
              >
                <el-button slot="reference" size="mini" type="primary"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="space-between">
          <el-col class="el-col-left" :span="12">
            用户数据托管在JsonServer 文件中，支持CRUD 请慎重操作
          </el-col>
          <el-col
            class="el-col-right"
            :span="12"
            type="flex"
            justify="space-between"
          >
            <el-pagination
              layout="prev, pager, next"
              :total="tableData.length"
              :page-size="pageSize"
              @current-change="currentChange"
            >
            </el-pagination>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 新增用户界面-->
    <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          status-icon
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="名称" prop="name">
            <el-input
              type="text"
              v-model="ruleForm.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              type="text"
              v-model="ruleForm.email"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="ruleForm.phone"></el-input>
          </el-form-item>
          <el-form-item>
            <el-row>
              <el-col :span="2">城市</el-col>
              <el-col :span="6">
                <el-input v-model="ruleForm.city"></el-input
              ></el-col>
              <el-col :span="2">街道</el-col>
              <el-col :span="6">
                <el-input v-model="ruleForm.street"></el-input
              ></el-col>
              <el-col :span="2">邮编</el-col>
              <el-col :span="6">
                <el-input v-model="ruleForm.zipcode"></el-input
              ></el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitUserForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [], //表格所有数据
      searchValue: "", //搜索关键字
      pageSize: 6, //每页多少条
      pageNum: 1, //当前页
      dialogFormVisible: false,
      ruleForm: {
        name: "",
        username: "",
        email: "",
        phone: "",
        address: {
          city: "Gwenborough",
          street: "Kulas Light",
          zipcode: "92998-3874",
        },
      },
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
           email: [
          { required: true, message: "请输入邮箱，作为密码", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.query(); //查询英雄
  },
  methods: {
    query() {
      fetch("http://47.241.102.141:3000/users")
        .then((response) => response.json())
        .then((data) => {
          this.tableData = data; //数组中存储完整数据 通过filter实现
        });
    },
    currentChange(val) {
      this.pageNum = val;
    },
    handleDesc(index, row) {
      console.log(index, row);
      this.$router.replace({
        path: "/dashboard/user-desc",
        query: { id: row.id },
      });
    },
    handleDelete(id) {
      fetch("http://47.241.102.141:3000/users/" + id, {
        method: "delete",
      })
        .then((response) => response.json())
        .then((data) => {
          console.log(data);
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
          });

          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].id == id) {
              this.tableData.splice(i, 1);
              break;
            }
          }
        });
    },
    onSubmitUserForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          fetch("http://47.241.102.141:3000/users", {
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(this.ruleForm),
          })
            .then((response) => response.json())
            .then((data) => {
              //JsonServer 默认返回插入的数据
              this.tableData.push(data);
              this.$notify({
                title: "成功",
                message: "这是一条成功的提示消息",
                type: "success",
              });
              this.$refs["ruleForm"].resetFields();
            });
        } else {
          this.$notify({
            title: "警告",
            message: "没有通过表单验证",
            type: "warning",
          });
          return false;
        }
      });
    },
  },
  computed: {
    //u过滤数据实现分页和搜索效果  这个做法有点难理解  建议使用两个数组 倒换数据
    filterTableData() {
      //先搜索
      let newTable = this.tableData.filter((item) => {
        return !this.searchValue || item.name.includes(this.searchValue.trim());
      });

      //在分页  搜索的数据必须在第一页
      if (newTable.length <= this.pageSize) {
        return newTable;
      } else {
        let finalTable = newTable.filter((item, index) => {
          let start = (this.pageNum - 1) * this.pageSize;
          let end = start + this.pageSize;
          return index >= start && index < end;
        });
        return finalTable;
      }
    },
  },
};
</script>
<style>
.box-card {
  width: 90%;
}

.box-header {
  display: flex;
  justify-content: space-between;
}

.el-row {
  padding-top: 20px;
}

.el-col-left {
  text-align: left;
}
.el-col-right {
  text-align: right;
}
</style>